<script setup>
import { ref, onMounted, onUnmounted, watch } from 'vue';
import { useRouter } from 'vue-router';
import { ElLoading } from 'element-plus';
import VideoCard from '../components/VideoCard.vue';
import UploadCard from '../components/UploadCard.vue';
import EmptyContent from '../components/EmptyContent.vue';
import { getMyVideosApi, getUserVideosApi } from '@/api/video'; // 导入获取用户视频的API
import { useVideoPlayerStore } from '@/store/modules/videoPlayer';

// 接收用户ID作为props
const props = defineProps({
  userId: {
    type: String,
    default: '' // 空字符串表示当前登录用户
  }
});

const videoPlayerStore = useVideoPlayerStore();

const handleVideoClick = (video) => {
  console.log('点击视频:', video);
  // 确保使用正确的视频ID，兼容两种格式
  const videoId = String(video.video_id || video.id); 
  // 传递完整视频对象，确保模态框能获取所有必要信息
  videoPlayerStore.openVideoModal(videoId, video);
};

const router = useRouter();

// 视频数据状态
const userVideos = ref([]);
const hasVideos = ref(false);
const isLoading = ref(false);
const noMoreVideos = ref(false);
const error = ref(null);

// 分页参数
const page = ref(1);
const pageSize = 12;
const totalPages = ref(1);
const loadingObserver = ref(null);

// 加载视频数据
const loadUserVideos = async (isFirstLoad = false) => {
  if (isLoading.value || (noMoreVideos.value && !isFirstLoad)) return;

  isLoading.value = true;
  error.value = null;

  try {
    // 如果是第一次加载或重新加载，重置页码和视频列表
    if (isFirstLoad) {
      page.value = 1;
      userVideos.value = [];
      noMoreVideos.value = false;
    }
    const params = {
      page: page.value,
      limit: pageSize,
      status: "all"
    };

    let response
    if (props.userId) {
      response = await getUserVideosApi(props.userId, params);
    } else {
      response = await getMyVideosApi(params);
    }

    // 这里假设API返回格式为 { data: [...], total: number, totalPages: number }
    if (response && response.data) {
      if (isFirstLoad) {
        userVideos.value = response.data;
      } else {
        userVideos.value = [...userVideos.value, ...response.data];
      }

      totalPages.value = response.pagination.totalPages || Math.ceil(response.total / pageSize);
      hasVideos.value = userVideos.value.length > 0;
      
      // 判断是否还有更多视频
      if (page.value >= totalPages.value) {
        noMoreVideos.value = true;
      } else {
        page.value++;
      }
    } else {
      noMoreVideos.value = true;
    }
  } catch (err) {
    console.error('加载视频失败:', err);
    error.value = '加载视频失败，请稍后重试';
  } finally {
    isLoading.value = false;
  }
};

// 初始化观察者以实现滚动加载更多
const initIntersectionObserver = () => {
  const options = {
    root: null, // 使用视口作为根
    rootMargin: '0px 0px 200px 0px', // 提前200px触发加载
    threshold: 0.1 // 当目标元素有10%可见时触发
  };

  loadingObserver.value = new IntersectionObserver((entries) => {
    if (entries[0].isIntersecting && !isLoading.value && !noMoreVideos.value) {
      loadUserVideos();
    }
  }, options);

  // 观察加载指示器元素
  const target = document.querySelector('#loadingIndicator');
  if (target) {
    loadingObserver.value.observe(target);
  }
};

// 上传视频
const uploadVideo = () => {
  router.push('/creation');
};

// 删除视频
const deleteVideo = async (videoId) => {
  try {
    // 这里添加删除视频的API调用
    // await deleteVideoApi(videoId);
    
    // 成功后重新加载视频列表
    loadUserVideos(true);
  } catch (error) {
    console.error('删除视频失败:', error);
  }
};

watch(
  () => props.userId,
  () => {
    console.log('用户ID变化:', props.userId);
    loadUserVideos(true);
  }
);

// 组件挂载时初始化
onMounted(() => {
  // 加载第一页视频
  loadUserVideos(true);
  
  // 初始化观察者
  setTimeout(() => {
    initIntersectionObserver();
  }, 500);
});

// 组件卸载时清理观察者
onUnmounted(() => {
  if (loadingObserver.value) {
    loadingObserver.value.disconnect();
  }
});
</script>

<template>
  <div class="content-panel">
    <div class="header-row">
      <h3>{{ props.userId ? 'Ta的视频' : '我的视频' }}</h3>
    </div>
    
    <!-- 错误提示 -->
    <div v-if="error" class="error-message">
      {{ error }}
      <el-button type="text" @click="loadUserVideos(true)">重试</el-button>
    </div>
    
    <!-- 有视频数据时显示视频列表 -->
    <div v-if="hasVideos || isLoading" class="video-list-container">
      <div class="video-list">
        <VideoCard 
          v-for="video in userVideos" 
          :key="video.video_id" 
          :video="video"
           :show-controls="!props.userId"
          @view-detail="handleVideoClick(video)"
          @delete="deleteVideo"
        />
        <UploadCard @upload="uploadVideo" v-if="!userId"/>
      </div>
      
      <!-- 加载指示器和底部提示 -->
      <div id="loadingIndicator" class="loading-indicator">
        <div v-if="isLoading" class="loading-spinner">
          <el-loading />
          <span>加载中...</span>
        </div>
        <div v-else-if="noMoreVideos && userVideos.length > 0" class="no-more-videos">
          — 已经到底啦 —
        </div>
      </div>
    </div>
    
    <!-- 无视频内容时显示空状态 -->
    <EmptyContent 
      v-else-if="!isLoading && !hasVideos" 
      icon="🎬"
      text="暂无视频内容"
      button-text="上传视频"
      :is-mine="!props.userId"
      @action="uploadVideo"
    />
  </div>
</template>

<style scoped lang="scss">
.content-panel {
  display: flex;
  flex-direction: column;
  height: 100%;
  padding-bottom: 16px;

  .header-row {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 16px;
  }

  h3 {
    margin-top: 8px;
    margin-bottom: 0;
    font-weight: 500;
    font-size: 1.4rem;
    color: #ffffff;
    border-left: 4px solid #0096ff;
    padding-left: 12px;
  }
}

.video-list-container {
  flex: 1;
  overflow-y: auto;
  overflow-x: hidden;
  padding-right: 4px;
  
  /* 平滑滚动 */
  scroll-behavior: smooth;
  
  /* 自定义滚动条 */
  &::-webkit-scrollbar {
    width: 4px;
  }

  &::-webkit-scrollbar-track {
    background: rgba(255, 255, 255, 0.1);
    border-radius: 4px;
  }

  &::-webkit-scrollbar-thumb {
    background: rgba(255, 255, 255, 0.2);
    border-radius: 4px;
  }

  &::-webkit-scrollbar-thumb:hover {
    background: rgba(255, 255, 255, 0.4);
  }
}

.video-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(180px, 1fr));
  gap: 20px;
  padding: 8px;
}

.loading-indicator {
  padding: 16px 0;
  display: flex;
  justify-content: center;
  align-items: center;
  height: 60px;
  width: 100%;
}

.loading-spinner {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: #99a3a7;
  gap: 8px;
  
  .el-loading {
    font-size: 24px;
    width: 24px;
    height: 24px;
    animation: rotate 1s linear infinite;
  }
  
  span {
    font-size: 14px;
  }
}

.no-more-videos {
  color: #99a3a7;
  font-size: 14px;
  text-align: center;
  padding: 10px 0;
  width: 100%;
  position: relative;
  
  &:before, &:after {
    content: '';
    position: absolute;
    top: 50%;
    height: 1px;
    width: 25%;
    background: rgba(255, 255, 255, 0.1);
  }
  
  &:before {
    left: 10%;
  }
  
  &:after {
    right: 10%;
  }
}

.error-message {
  padding: 12px;
  background-color: rgba(255, 73, 73, 0.1);
  border-radius: 8px;
  color: #ff6b6b;
  margin-bottom: 16px;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

@keyframes rotate {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}
</style>